import React, { useState, useEffect } from 'react';
import { useNavigate, Outlet, useLocation } from "react-router-dom";
import Header from "@/Components/Header/index.jsx";
import { Menu } from 'antd';
import { useSelector } from 'react-redux';

import './index.scss';

const items = [
  {
    label: '网络配置',
    key: 'web',
  },
  {
    label: '配置管理',
    key: 'config',
  },
  {
    label: '测试调试',
    key: 'test',
  },
  {
    label: '系统控制',
    key: 'system',
  },
  {
    label: '传感配置',
    key: 'sensor',
  }
];

// 创建映射对象
const keyToNameMap = {
  web: '网络配置',
  config: '配置管理',
  test: '测试调试',
  system: '系统控制'
};

function Home(props) {
  const isDark = useSelector(state => state.theme.isDark);
  const location = useLocation();
  const navigate = useNavigate();
  // 从路径中提取当前选中的 key
  const currentKey = location.pathname.split('/').filter(Boolean)[0] || 'web';

  const [current, setCurrent] = useState(currentKey);
  const [name, setName] = useState(keyToNameMap[currentKey] || '网络配置');

  useEffect(() => {
    const pathKey = location.pathname.split('/').filter(Boolean)[0] || 'web';

    setCurrent(pathKey);
    setName(keyToNameMap[pathKey] || '网络配置');
  }, [location.pathname]); // 依赖 location.pathname

  const onClick = (e) => {
    setCurrent(e.key);
    setName(keyToNameMap[e.key] || '网络配置');
    navigate(e.key);
  };

  return (
    <>
      <Header />
      <div className="navigation">
        <div className="menu">
          <Menu
            onClick={onClick}
            selectedKeys={[current]}
            mode="horizontal"
            items={items}
          />
        </div>
        <div className="breadcrumb">
          当前位置: 首页 {'>'} {name}
        </div>
      </div>
      <main>
        <Outlet />
      </main>
    </>
  );
}

export default Home;